const httpStatus = require('http-status');
const { User } = require('../models');
const ApiError = require('../utils/ApiError');

/**
 * 创建用户
 * @param {Object} userBody - 用户数据
 * @returns {Promise<User>} - 创建的用户
 */
const createUser = async (userBody) => {
  // 如果提供了邮箱，检查是否已被使用
  if (userBody.email && await User.isEmailTaken(userBody.email)) {
    throw new ApiError(httpStatus.BAD_REQUEST, '此邮箱已被使用');
  }
  
  // 如果提供了微信openid，检查是否已被使用
  if (userBody.wechatOpenid && await User.findOne({ wechatOpenid: userBody.wechatOpenid })) {
    throw new ApiError(httpStatus.BAD_REQUEST, '此微信账号已被绑定');
  }
  
  const user = await User.create(userBody);
  return user;
};

/**
 * 查询用户
 * @param {Object} filter - 过滤条件
 * @param {Object} options - 查询选项
 * @param {number} [options.limit] - 每页最大项数
 * @param {number} [options.page] - 当前页码
 * @param {string} [options.sortBy] - 排序字段
 * @param {boolean} [options.includeDeleted] - 是否包含已删除用户
 * @returns {Promise<Object>} - 查询结果，包含数据和分页信息
 */
const queryUsers = async (filter, options) => {
  const limit = options.limit && parseInt(options.limit, 10) > 0 ? parseInt(options.limit, 10) : 10;
  const page = options.page && parseInt(options.page, 10) > 0 ? parseInt(options.page, 10) : 1;
  const skip = (page - 1) * limit;
  
  const sortBy = options.sortBy || 'createdAt:desc';
  const [sortField, sortOrder] = sortBy.split(':');
  const sort = { [sortField]: sortOrder === 'desc' ? -1 : 1 };

  // 构建最终的查询条件
  const finalFilter = { ...filter };

  // 默认排除已删除用户，除非明确指定包含
  if (!options.includeDeleted && finalFilter.isDeleted === undefined) {
    finalFilter.isDeleted = false;
  }

  // 全局搜索逻辑
  if (options.search) {
    const searchQuery = { $regex: options.search, $options: 'i' };
    finalFilter.$or = [
      { name: searchQuery },
      { nickname: searchQuery },
      { email: searchQuery },
      // 如果有其他适合文本搜索的字段，也可以在这里添加，例如：
      // { phone: searchQuery }, 
    ];
  }

  const countPromise = User.countDocuments(finalFilter).exec();
  const usersPromise = User.find(finalFilter)
    .sort(sort)
    .skip(skip)
    .limit(limit)
    .exec();

  const [count, users] = await Promise.all([countPromise, usersPromise]);
  const totalPages = Math.ceil(count / limit);

  return {
    results: users,
    page,
    limit,
    totalPages,
    totalResults: count,
  };
};

/**
 * 根据ID获取用户
 * @param {string} id - 用户ID
 * @param {Object} [options] - 选项
 * @param {boolean} [options.includeDeleted] - 是否包含已删除用户
 * @returns {Promise<User>} - 用户
 */
const getUserById = async (id, options = {}) => {
  console.log('尝试根据ID获取用户:', id);
  
  if (!id) {
    console.error('获取用户时ID为空');
    return null;
  }
  
  try {
    const query = { _id: id };
    
    // 默认排除已删除用户，除非明确指定包含
    if (!options.includeDeleted) {
      query.isDeleted = false;
    }
    
    const user = await User.findOne(query);
    if (!user) {
      console.error('根据ID未找到用户:', id);
    } else {
      console.log('成功获取用户:', user.id);
    }
    return user;
  } catch (error) {
    console.error('根据ID获取用户出错:', error.message);
    return null;
  }
};

/**
 * 根据邮箱获取用户
 * @param {string} email - 用户邮箱
 * @returns {Promise<User>} - 用户
 */
const getUserByEmail = async (email) => {
  return User.findOne({ email, isDeleted: false });
};

/**
 * 根据微信openid获取用户
 * @param {string} openid - 微信openid
 * @returns {Promise<User>} - 用户
 */
const getUserByWechatOpenid = async (openid) => {
  return User.findOne({ wechatOpenid: openid, isDeleted: false });
};

/**
 * 更新用户
 * @param {string} userId - 用户ID
 * @param {Object} updateBody - 更新数据
 * @returns {Promise<User>} - 更新后的用户
 */
const updateUserById = async (userId, updateBody) => {
  // 查找用户时，也包括已逻辑删除的用户，以便可以更新他们的信息（如头像）
  const user = await getUserById(userId, { includeDeleted: true });
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, '用户不存在');
  }
  if (updateBody.email && (await User.isEmailTaken(updateBody.email, userId))) {
    throw new ApiError(httpStatus.BAD_REQUEST, '此邮箱已被使用');
  }
  Object.assign(user, updateBody);
  await user.save();
  return user;
};

/**
 * 逻辑删除用户（标记删除）
 * @param {string} userId - 用户ID
 * @returns {Promise<User>} - 删除的用户
 */
const softDeleteUserById = async (userId) => {
  const user = await getUserById(userId);
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, '用户不存在');
  }
  user.isDeleted = true;
  await user.save();
  return user;
};

/**
 * 物理删除用户
 * @param {string} userId - 用户ID
 * @returns {Promise<User>} - 删除的用户
 */
const deleteUserById = async (userId) => {
  const user = await getUserById(userId, { includeDeleted: true });
  if (!user) {
    throw new ApiError(httpStatus.NOT_FOUND, '用户不存在');
  }
  await user.remove();
  return user;
};

module.exports = {
  createUser,
  queryUsers,
  getUserById,
  getUserByEmail,
  getUserByWechatOpenid,
  updateUserById,
  softDeleteUserById,
  deleteUserById,
}; 